//
//  GCPresenter.m
//  CBHGroupCar
//
//  Created by mac on 2018/1/24.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "GCPresenter.h"

#import "Head.h"

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>

#endif
@interface GCPresenter()<CLLocationManagerDelegate>

@property (nonatomic,strong) GYLeadVC *leadVC;
@end

@implementation GCPresenter
#pragma mark - getter and setter
-(CLLocationManager *)locationManager
{
    if (!_locationManager) {
        //请求定位服务
        _locationManager=[[CLLocationManager alloc]init];
        _locationManager.delegate=self;
        _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
        if(![CLLocationManager locationServicesEnabled]||[CLLocationManager authorizationStatus]!=kCLAuthorizationStatusAuthorizedWhenInUse)
        {
            [_locationManager requestWhenInUseAuthorization];
        }
    }
    return _locationManager;
}
-(TTL_MainTabVC *)mainVC
{
    if (!_mainVC) {
        _mainVC = [[TTL_MainTabVC alloc]init];
        [self requestLastVersion];
    }
    return _mainVC;
}

-(AppDelegate *)appDelegate
{
    if (!_appDelegate) {
        _appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    }
    return _appDelegate;
}
-(GYLeadVC *)leadVC
{
    if (!_leadVC) {
        _leadVC = [GYLeadVC new];
    }
    return _leadVC;
}
#pragma mark - method


-(void)loadChatLogin
{
    
}
-(void)loadMain
{
    [self startUpdateLocationg];
    if ([[[NSUserDefaults standardUserDefaults]  objectForKey:kHasAppOpened] integerValue]==0 )
    {
        [self loadLead];
    }else{
        self.appDelegate.window.rootViewController = self.mainVC;
    }
}
-(void)loadLead
{
    self.appDelegate.window.rootViewController = self.leadVC;
}
-(void)loadLogin
{

    TKL_LoginVC *login = [TKL_LoginVC new];
    HMSNavigationController *nav = [[HMSNavigationController alloc]initWithRootViewController:login];
    [self.mainVC presentViewController:nav animated:YES completion:nil];
}
-(void)generalConfig
{
    //设置键盘事件
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.shouldResignOnTouchOutside = YES;
    //    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.preventShowingBottomBlankSpace = YES;
    manager.toolbarTintColor = Main_Color;
    manager.toolbarDoneBarButtonItemText = @"完成";
    [[UITextField appearance] setTintColor:Main_Color];
    [[UITextView appearance]setTintColor:Main_Color];
    
}
-(void)startUpdateLocationg
{
    [self.locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *currLocation = [locations lastObject];

    [_locationManager stopUpdatingLocation];
    
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:currLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        for (CLPlacemark *place in placemarks)
        {
        }
    }];
}
-(void)requestLastVersion
{
    @WeakSelf;
    NSMutableDictionary *para = [NSMutableDictionary new];

    [para setObject:@"ios" forKey:@"os"];
    [para setObject:@"1" forKey:@"plat"];
    NSString *interface = @"check_version";
    [[InterfaceManager shareInterface]requetInterface:interface withParameter:para handler:^(NSDictionary *info, InterfaceStatusModel *infoModel) {
        if (0 == infoModel.errorCode) {
            NSDictionary *data = infoModel.data;
            if ([data isKindOfClass:[NSDictionary class]])
            {
                
                [selfp setCon_phone:[data objectForKey:@"contact_phone"]];
                NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
                NSString *currentVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
                NSString *lastVersion = data[@"build_number"];
                
                NSInteger currentTag= [[currentVersion stringByReplacingOccurrencesOfString:@"." withString:@""] intValue];
                NSInteger lastTag= [lastVersion intValue];
                
                if (currentTag<lastTag)
                {
                    
                    if ([[data objectForKey:@"pass"] intValue]==1)
                    {
                        [selfp setCanShow:YES];
                        NSString *url = [NSString stringWithFormat:@"%@",data[@"url"]];
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:data[@"text"] message:lastVersion delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
                        [alert showAlertViewWithCompleteBlock:^(NSInteger buttonIndex) {
                            if (1 == buttonIndex) {
                                NSURL *URL = [NSURL URLWithString:url];
                                [[UIApplication sharedApplication]openURL:URL];
                            }
                        }];
                        
                    }else
                    {
                        [selfp setCanShow:NO];
                    }
                }else
                {
                    if ([[data objectForKey:@"pass"] intValue]==1)
                    {
                         [selfp setCanShow:YES];
                    }else
                    {
                        [selfp setCanShow:NO];
                    }
                }
            }
        }
    }];
}
-(void)phoneCall:(NSString *)phone
{
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",phone];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}
-(void)showOriginalImages:(NSArray *)originalImages andImageViews:(NSArray *)sourceImgageViews withIndex:(NSInteger)index
{
    // 1. 创建photoBroseView对象
    PYPhotoBrowseView *photoBroseView = [[PYPhotoBrowseView alloc] init];
    
    // 2.1 设置图片源(UIImageView)数组
    photoBroseView.imagesURL = originalImages;
    if (sourceImgageViews) photoBroseView.sourceImgageViews = sourceImgageViews;
    photoBroseView.currentIndex = index;
    photoBroseView.frameFormWindow = CGRectMake(0, 0, SCREEN_WIDTH, WFCGFloatY(200));
    photoBroseView.frameToWindow = photoBroseView.frameFormWindow;
    // 3.显示(浏览)
    [photoBroseView show];
}
-(void)showOriginalImages:(NSArray *)originalImages andImageViews:(NSArray *)sourceImgageViews
{
    [self showOriginalImages:originalImages andImageViews:sourceImgageViews withIndex:0];
}
///缓存大小
-(float)fileSizeAtPath:(NSString *)path
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:path]){
        long long size = [fileManager attributesOfItemAtPath:path error:nil].fileSize;
        return size / 1024.0 / 1024.0;
    }
    return 0;
}
-(float)folderSizeAtPath:(NSString *)path
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    float folderSize = 0.0;
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles = [fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
            folderSize += [self fileSizeAtPath:absolutePath];
        }
        // SDWebImage框架自身计算缓存的实现
        folderSize += [[SDImageCache sharedImageCache] getSize]/1024.0/1024.0;
        return folderSize;
    }
    return 0;
}
///清除缓存
-(void)clearCache:(NSString *)path
{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            //如有需要，加入条件，过滤掉不想删除的文件
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
        [FTIndicator showSuccessWithMessage:@"已经清除缓存~"];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"cache_clear_noti" object:nil];
    }];
}
#pragma mark - life
+(instancetype)shareInterface
{
    static GCPresenter *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!manager) {
            manager = [[GCPresenter alloc]init];
        }
    });
    return manager;
}
-(void)dealloc
{
    [[InterfaceManager shareInterface]removeObserver:self forKeyPath:@"netStatus"];
}
-(instancetype)init
{
    if (self = [super init]) {
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
        UIWindow *window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
        [window makeKeyWindow];
        [window makeKeyAndVisible];
        window.backgroundColor = Main_Color_White;
        self.appDelegate.window = window;
        [self generalConfig];
        if (!_appDelegate.window.rootViewController) {

        }
        //
        [[InterfaceManager shareInterface].specialInterfaces addObject:@"getLastVersion"];
        [[InterfaceManager shareInterface]addObserver:self forKeyPath:@"netStatus" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:nil];
    }
    return self;
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"netStatus"]) {
//        NetStatusT old = [change[@"old"] integerValue];
        NetStatusT new = [change[@"new"] integerValue];
        if (NetStatusWWAN == new) {
            
        }
        if (NetStatusWiFi == new) {
        }
        if (NetStatusReachable == new) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络不可用,请检查您的网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert showAlertViewWithCompleteBlock:^(NSInteger buttonIndex) {
//                if (1 == buttonIndex) {
//                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"App-Prefs:root=WIFI"]];
//                }
            }];
        }
    }
}
@end
